package org.rcy.ruicingmarket.oss.view;

import org.rcy.ruicingmarket.common.utils.CollectionBeanUtils;
import org.rcy.ruicingmarket.view.Menu;
import org.rcy.ruicingmarket.view.ViewResourceVo;
import org.rcy.ruicingmarket.view.ViewVo;
import org.rcy.ruicingmarket.view.PrimaryMenuVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/10/10 9:41
 */
@Transactional
@Service
public class ViewService {
	@Autowired
	private OssViewDao ossViewDao;

	public List<ViewResourceVo> getViewListByUser(Long userId) {
		List<OssView> viewList = ossViewDao.getViewListByUser(userId);
		List<ViewResourceVo> viewResourceVos = new ArrayList<>();
		if(!viewList.isEmpty()){
			Map<Menu, List<OssView>> viewListAfterGrouping = viewList.stream().collect(Collectors.groupingBy(OssView::getMenu));
			Set<Menu> menus = viewListAfterGrouping.keySet();
			for (Menu menu : menus) {
				ViewResourceVo viewResourceVo = new ViewResourceVo();
				viewResourceVo.setPrimaryMenu(new PrimaryMenuVo(menu.name(),menu.getDisName()));
				List<OssView> ossViews = viewListAfterGrouping.get(menu);
				List<ViewVo> viewVos = CollectionBeanUtils.copyListProperties(ossViews, ViewVo::new, (p, v) -> {
					v.setPrimaryMenuVo(new PrimaryMenuVo(p.getMenu().name(), p.getMenu().getDisName()));
				});
				viewResourceVo.setViewVos(viewVos);
				viewResourceVos.add(viewResourceVo);
			}
		}

		return viewResourceVos;
	}

	public void createOrUpdate(ViewVo viewVo) {
		OssView ossView = convertToPo(viewVo);
		if(ossView.getId() == null) {
			ossView.setCreateTime(new Date());
		}
		ossViewDao.save(ossView);
	}

	private ViewVo convertToVo(OssView ossView) {
		ViewVo viewVo = new ViewVo();
		BeanUtils.copyProperties(ossView, viewVo);
		viewVo.setPrimaryMenuVo(new PrimaryMenuVo(ossView.getMenu().name(), ossView.getMenu().getDisName()));
		return viewVo;
	}
	private OssView convertToPo(ViewVo vo){
		OssView ossView = new OssView();
		BeanUtils.copyProperties(vo, ossView);
		if(vo.getViewId() != null) {
			ossView.setId(vo.getViewId());
		}
		ossView.setMenu(Menu.valueOf(vo.getPrimaryMenuVo().getName()));
		return ossView;
	}
}
